package cathe

import (
	"cart_srv/cart"
	"fmt"
	"strconv"
)

// 添加购物车
func CartAdd(userId, goodsId int, getMap map[string]interface{}) error {
	key := fmt.Sprintf("cart:%d:%d", userId, goodsId)
	return Rdb.HMSet(ctx, key, getMap).Err()
}

// 判断商品存不存在
func ExistsGoods(userId, goodsId int) bool {
	key := fmt.Sprintf("cart:%d:%d", userId, goodsId)
	return Rdb.Exists(ctx, key).Val() == 1
}

// 如果商品存在则增加商品数量
func UpdateGoodsNum(userId, goodsId, num int) error {
	key := fmt.Sprintf("cart:%d:%d", userId, goodsId)
	return Rdb.HIncrBy(ctx, key, "num", int64(num)).Err()
}

// 购物车列表
func CartList(userId int) (cartList []*cart.CartList, err error) {
	key := fmt.Sprintf("cart:%d:*", userId)
	keys := Rdb.Keys(ctx, key).Val()
	for _, k := range keys {
		cartgoods := Rdb.HGetAll(ctx, k).Val()
		price, _ := strconv.ParseFloat(cartgoods["price"], 64)
		num, _ := strconv.Atoi(cartgoods["num"])
		goodsId, _ := strconv.Atoi(cartgoods["goodsId"])
		cartList = append(cartList, &cart.CartList{
			Title:   cartgoods["title"],
			Image:   cartgoods["image"],
			Price:   float32(price),
			Num:     int64(num),
			GoodsId: int64(goodsId),
		})

	}
	return
}
